package com.cd.university.common.task;

import com.cd.university.common.UniversityConstants;
import com.cd.university.common.obs.ObsUtils;
import com.cd.university.db.mapper.SystemLogMapper;
import com.cd.university.db.pojo.SystemLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;

/**
 * @author 陈栋
 * @create 2021/11/8 19:36
 */
@Component
public class LogFileUpLoadTask {

    @Autowired
    private ObsUtils obsUtils;

    @Autowired
    private SystemLogMapper systemLogMapper;

    /**
     * 项目的系统文件上传到华为的Obs中,每天晚上11点定时执行
     */
    @Async
    @Scheduled(cron = "0 0 23 * * ?")
    public void SystemLogFileUpdate() {
        File myLogs = new File("myLogs");
        File[] tempList = myLogs.listFiles();
        for (File file : tempList) {
            // 拿到文件的Url
            String fileUrl = obsUtils.uploadFile(file, file.getName(),UniversityConstants.SYSTEM_LOG_FILE_FOLDER);

            // 从数据库中更新
            SystemLog systemLog = new SystemLog();
            systemLog.setSystemLogFileName(file.getName());
            systemLog.setSystemLogTime(new Date(System.currentTimeMillis()));
            systemLog.setSystemLogUrl(fileUrl);
            systemLog.setSystemLogSize((double)file.length());

            int row = systemLogMapper.updateByFileName(systemLog);

            // 如果更新的行数小于1，说明数据库中没有,那么就插入到数据库中
            if (row<1) {
                systemLogMapper.insertSelective(systemLog);
            }
        }
    }

    @Async
    public boolean deleteSystemLog(String fileName) {
        File file = new File("myLogs/" + fileName);
        return file.delete();
    }
}
